package cn.afactory.tygz.ui.base.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.harwkin.nb.camera.model.PicsItem;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.UserListType;
import cn.afactory.tygz.model.SnsCommentInfo;
import cn.afactory.tygz.model.SnsSubjectDetail;
import cn.afactory.tygz.model.SnsSubjectDetailList;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.adapter.NearByForumsAdapter;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.ImageUtils;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.sns.TimeUtil;
import cn.afactory.tygz.ui.base.views.AutoGridView;
import cn.afactory.tygz.ui.sns.PublishSubjectActivity;
import cn.afactory.tygz.ui.sns.SubjectDetailActivity;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

/**
 * 附近的事
 */
public class NearByForumsFragment extends BaseFragment implements NearByForumsAdapter.OnItemClickListener {

    private static final String TAG = NearByForumsFragment.class.getSimpleName();
    private NearByForumsAdapter mAdapter;
    private List<SnsSubjectDetail> mList = new ArrayList<>();
    private SnsControler mController;

    private LinearLayout mForumsAddLinearLayout;
    public static final String PUBLISH_BROADCAST_ACTION = "PublishAction";
    private PublishSubjectBroadcastReceiver mBroadcastReceiver;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case SnsControler.MSG_NEAR_BY_FORUMS_OK:
                if (msg.obj instanceof SnsSubjectDetailList) {
                    hideErrorPage(-1);
                    SnsSubjectDetailList t = (SnsSubjectDetailList) msg.obj;

                    if (t.rows != null && t.rows.size() >= 0) {
                        try {
                            if (msg.arg1 == SnsControler.MSG_DATA_FROM_CACHE && mAdapter.getCount() == 0 && mLastReqTime == 0) {
                                mList.addAll(t.rows);
                            } else {
                                if (mLastReqTime == 0) {
                                    mList.clear();
                                }
                                mList.addAll(t.rows);
                                mLastReqTime = t.rows.get(t.rows.size() - 1).addTime;
                            }
//                            mController.removeDuplicate(mList);
                            //是否显示置顶链接VIEW
                            mAdapter.setData(mList);
                            mPageIndex = (mList.size()/mPageSize) + 1;
//                            setListListener();

                            if (plistview.isRefreshing()) {
                                plistview.onRefreshComplete();
                            }
                            if (t.rows.size() < mPageSize) {
                                plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                plistview.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (mAdapter.getCount() == 0) {
                            showNullPage(true);
                        }
                    }
                }
                break;
            case SnsControler.MSG_NEAR_BY_FORUMS_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadDatas();
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, "获取附近的动态失败！"/*StringUtil.handlerErrorCode(mContext, msg.arg1)*/);
                }
                break;
        }

        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addTitleBar = false;
        mController = new SnsControler(mContext,mUIHandler,"NearByForums");
        mBroadcastReceiver = new PublishSubjectBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PUBLISH_BROADCAST_ACTION);
        getActivity().registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fg_near_by_forums, null);
        initViews(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mController.loadCacheData();
        initData();
    }

    private void initViews(View v){
        plistview = (PullToRefreshListView)v.findViewById(R.id.lv_forums_list);

        mAdapter = new NearByForumsAdapter(getActivity(),mList);
        plistview.setAdapter(mAdapter);

        plistview.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView lv = plistview.getRefreshableView();
                if (position >= lv.getHeaderViewsCount()) {
                    position -= lv.getHeaderViewsCount();
                }
                SnsSubjectDetail snsSubjectDetail = (SnsSubjectDetail) mAdapter.getItem(position);
                Intent intent = new Intent(mContext, SubjectDetailActivity.class);
                intent.putExtra(SubjectDetailActivity.SUBJECT_DETAIL_TAG, snsSubjectDetail);
                startActivity(intent);
            }
        });

        mForumsAddLinearLayout = (LinearLayout)v.findViewById(R.id.nearby_forums_add);
        mForumsAddLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, PublishSubjectActivity.class);
                startActivityForResult(intent, PublishSubjectActivity.PUBLISH_REQUEST_CODE);
            }
        });

        mAdapter.setItemClickListener(this);

        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadDatas();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadSubjectData(false);
            }
        });
    }


    private void initData(){
        startLoadDatas();
    }

    public void startLoadDatas(){
        startLoadSubjectData(true);
    }

    /**
     * 加载listview数据
     */
    private int mPageIndex = 1;
    private int mPageSize = 10;
    private long mLastReqTime = System.currentTimeMillis();
    protected void startLoadSubjectData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mLastReqTime = 0;
            mList.clear();
        }
        if (null == mController) {
            mController = new SnsControler(getActivity(),mUIHandler,"NearByForums");
        }
        mController.loadNearByForumsData(mPageIndex,mPageSize);
    }

    @Override
    public void onPraise(TextView v, SnsSubjectDetail item) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (item != null && item.id >= 0) {
            mController.doPraiseToSubject(v, item);
        }
    }

    @Override
    public void onPraise(AutoGridView autoGridView, TextView v, SnsSubjectDetail item) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (item != null && item.id >= 0) {
            mController.doPraiseToSubject(autoGridView, v, item);
        }
    }

    @Override
    public void onClickImage(int position, List<String> mPath) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (mPath != null) {
            ArrayList<PicsItem> list = new ArrayList<>();
            for (String tmp : mPath) {
                PicsItem picsItem = new PicsItem();
                picsItem.image = ImageUtils.getBigImageFullPath(tmp);
                list.add(picsItem);
            }
            NaviUtils.gotoViewBigImageActivity(getActivity(),list, position, false, false);
        }
    }

    @Override
    public void onClickTopic(String topic, long topicId) {
        NaviUtils.gotoTopicDetailActivity(mContext, topicId);
    }

    @Override
    public void onClickShare(SnsSubjectDetail item) {
        DialogUtil.showShareDialog(getActivity(), "分享Title",
                item.content,
                null,
                null,
                null,
                null,
                null,
                null);
    }

    @Override
    public void onClickIcon(SnsSubjectDetail item) {
        NaviUtils.gotoUserProfileActivity(getActivity(), item.userId, item.nickName);
    }

    @Override
    public void onClickCommentIcon(SnsCommentInfo commentInfo) {
        NaviUtils.gotoUserProfileActivity(getActivity(), commentInfo.userId, commentInfo.userName);
    }

    @Override
    public void onClickTextContent(SnsSubjectDetail item) {
        Intent intent = new Intent(mContext, SubjectDetailActivity.class);
        intent.putExtra(SubjectDetailActivity.SUBJECT_DETAIL_TAG, item);
        startActivity(intent);
    }

    @Override
    public void onClickSubjectList(String str) {

    }

    @Override
    public void onClickComment(SnsSubjectDetail item) {
        NaviUtils.gotoSubjectDetail(getActivity(),item);
    }

    @Override
    public void onClickCompany(SnsSubjectDetail item) {
        NaviUtils.gotoUserList(mContext, -1, item.company, item.companyId, 0, UserListType.COMPANY_USER);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == PublishSubjectActivity.PUBLISH_RESULT_CODE) {
//            startLoadDatas();
        }
    }

    public class PublishSubjectBroadcastReceiver extends BroadcastReceiver {

        public static final String TAG = "PublishSubjectBroadcastReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            startLoadDatas();
        }
    }

}

